﻿using Microsoft.EntityFrameworkCore;
using Project.Common.Cache;
using Project.DTO;
using Project.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Project.Service
{
    public partial class OrderService
    {
        
        /// <summary>
        /// 生成订单顺序号
        /// </summary>
        /// <returns></returns>
        private string CreateOrderNo()
        {
            const string CACHENAME = "NoObj";  // 缓存的key

            var obj = new OrderNoCache() { Date = DateTime.Now.Date.ToString("yyyyMMdd"), Number=1 };
            if (CacheHelper.Exists(CACHENAME))
            {
                obj = CacheHelper.Get(CACHENAME) as OrderNoCache;
                obj.Date = DateTime.Now.Date.ToString("yyyyMMdd");
                obj.Number++;
            }

            CacheHelper.Set(CACHENAME, obj);


            string sno = "";
            for (int i = 1; i < 6 - obj.Number.ToString().Length; i++)
            {
                sno = "0" + sno;
            }

            return DateTime.Now.ToString("yyyyMMddhhmmss") + sno+obj.Number;
        }



        public override async Task<int> AddAsync(Order obj)
        {
            obj.OrderNo = CreateOrderNo();
            baseRepostory.Add(obj);
            int row = await unitOfWork.SaveChangesAsync();
            return row;
        }



        public override async Task<int> DeleteAsync(Guid id)
        {
            var order = await baseRepostory.FindAsync<Order>(id);
            if (order.State < 2)  // 如果是未接单或草稿
            {
                return await this.DeleteAsync(id);
            }
            return await this.MarkDeleteAsync(id);
        }



        public async Task<OrderPost> GetOrderAsync(Guid id)
        {
            var order = await baseRepostory.Find<Order>(o => o.Id == id).Include("")
                .Select(o => mapper.Map<OrderPost>(o))
                .FirstOrDefaultAsync();
            return order;   
        }


    }
}
